﻿namespace SenenFernandez.SmartExtensionMethods
{
    using System;
    using System.Reflection;
    using System.Runtime.InteropServices;
    using System.Threading;
    using System.Windows;

    public static class SmartInstance
    {
        private static Mutex instance;

        public static bool JustOneApplication(this string windowTitle)
        {
            bool isNewInstance = false;
            var assembly = Assembly.GetEntryAssembly();
            if (assembly != null)
            {
                instance = new Mutex(true, assembly.FullName, out isNewInstance);
                if (!isNewInstance)
                {
                    instance = null;
                    var handle = IntPtr.Zero.FindWindowEx(IntPtr.Zero, null, windowTitle);
                    handle.RestoreWindow();
                    if (Application.Current != null)
                    {
                        Application.Current.Shutdown();
                    }
                    else
                    {
                        Environment.Exit(0);
                    }
                }
            }
            return isNewInstance;
        }
    }
}
